from fastapi import APIRouter
from fastapi_amis_admin.globals.deps import AsyncSess, SyncSess
from sqlalchemy import select, text

from .models import Category
from ..common import ApiResult, PageParams, PageResult, DemoException

router = APIRouter()


@router.post("/page")
def page(params: PageParams, sess: SyncSess):
    raise DemoException(err_msg="测试错误！！！")
    offset = (params.page - 1) * params.size
    sql_where = []
    if not params and not params.params['name'] is None:
        sql_where.append(Category.name.contains(params.params['name']))
    query = sess.query(Category).where(*sql_where)
    results = query.offset(offset).limit(params.size).all()

    total = query.count()
    return PageResult(page=params.page, size=params.size, total=total, list=results)

@router.get("/detail")
def detail(id:int, sess: SyncSess):
    obj = sess.get(Category, id)
    return ApiResult(data=obj)

@router.post("/save")
def save(data:Category, sess: SyncSess):
    sess.add(data)
    return ApiResult()

@router.put("/update")
def update(data:Category, sess: SyncSess):
    print(dict(data))
    sess.query(Category).filter(Category.id == data.id).update(dict(data))
    return ApiResult()

@router.delete("/delete")
def delete(id:int, sess: SyncSess):
    sess.query(Category).filter(Category.id == id).delete()
    return ApiResult()



@router.get('/hello')
async def hello(name: str = '') -> str:
    return f'hello {name}'


@router.get("/test_sync_db", summary="测试同步数据库操作")
def test_sync_db(name: str,sess: SyncSess):
    # obj=sess.get(Category, id)
    obj = sess.query(Category).from_statement(text("SELECT * FROM blog_category where name like :name")).params(name=name).all()
    return obj
    # do something
    # stmt = select(Category).where(Category.id == id)
    # result = sess.execute(stmt)
    # return result.scalar()


@router.get("/test_async_db", summary="测试异步数据库操作")
async def test_async_db(id: int, sess: AsyncSess):
    obj=await sess.get(Category, id)
    return obj
    # do something
    # stmt = select(Category).where(Category.id == id)
    # result = await sess.execute(stmt)
    # return result.scalar()

# from fastapi_user_auth.globals.deps import CurrentUser
#
# @router.get("/get_user", summary="获取当前登录用户")
# async def get_user(user: CurrentUser):
#     return user